package mest.config.intercepors;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import mest.entity.User;
import mest.util.RedisUtil;
import mest.util.ResultObj;

/**
 *@Title LoginInterceptor.java
 *@description TODO
 *@time 2019年12月5日 上午10:35:21
 *@author Twinson Wong
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {

	@Resource
    private RedisUtil redisUtil;
	
	//这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每一个项目对于登陆的实现逻辑都有所区别，我这里使用最简单的Session提取User来验证登陆。
        HttpSession session = request.getSession();
        if (request.getRequestURI().contains("/mest/login/")) {
			return true;
		}
        //这里的User是登陆时放入session的
        
        User user = (User) session.getAttribute("user");
        String FileName="";
        //redisUtils.get()
        //如果session中没有user，表示没登陆
        if (user == null){
        	
        	//response.sendRedirect("http://127.0.0.1:8080/login");
        	//response.sendRedirect("http://www.baidu.com");
            //response.sendRedirect(request.getHeader("Origin")+"/index.html");
        	//response.sendRedirect("/mest/login/showLogin");
        	
        	//System.out.println("没有登陆:"+request.getRequestURL()+","+request.getRequestURI());
            //这个方法返回false表示忽略当前请求，如果一个用户调用了需要登陆才能使用的接口，如果他没有登陆这里会直接忽略掉
            //当然你可以利用response给用户返回一些提示信息，告诉他没登陆
        	ResultObj result = new ResultObj(ResultObj.CODE_LOGIN_REQUIRED,ResultObj.SESSION_INVALIDE,0,"");
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(result));
            writer.flush();
            writer.close();
            return false;
        }else {
            return true;    //如果session里有user，表示该用户已经登陆，放行，用户即可继续调用自己需要的接口
        }
    }
 
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }
 
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    	
    }

}
